package com.gxuwz.leaveSystem.Util;

import com.gxuwz.leaveSystem.entity.Leave;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

public class ExcelExporter {

    public static byte[] exportLeavesToExcel(List<Leave> leaves) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Leaves");

        // 创建表头
        Row headerRow = sheet.createRow(0);
        String[] headers = {"Leave ID", "Course ID", "Reason", "Daynum", "Student No", "Apply Time", "Status", "Audit Time", "Opinion"};
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }

        // 填充数据
        int rowNum = 1;
        for (Leave leave : leaves) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(leave.getLeaveID());
            row.createCell(1).setCellValue(leave.getCourseID());
            row.createCell(2).setCellValue(leave.getReason());
            row.createCell(3).setCellValue(leave.getDaynum());
            row.createCell(4).setCellValue(leave.getStuNo());
            row.createCell(5).setCellValue(leave.getApplytime().toString());
            row.createCell(6).setCellValue(leave.getStatus());
            row.createCell(7).setCellValue(leave.getAudittime().toString());
            row.createCell(8).setCellValue(leave.getOpinion());
        }

        // 将Workbook转换为字节数组
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        workbook.write(outputStream);
        workbook.close();

        return outputStream.toByteArray();
    }
}
